<script setup>
import {ref} from "vue";
import {UploadFilled} from '@element-plus/icons-vue';

const message = ref("");
const messages = ref([]);
const imageFile = ref(null); // 用于存储上传的图片
const imagePreview = ref(""); // 用于存储图片的Base64编码

const sendMessage = async () => {
  if (message.value.trim()) {
    // 添加用户消息
    messages.value.push({text: message.value, user: "me"});

    // 创建一个空的 bot 消息对象
    const botMessage = {text: "", user: "bot"};
    messages.value.push(botMessage); // 先将 bot 消息添加到 messages 中
    console.log("用户信息",message.value)
    try {
      const response = await fetch("http://127.0.0.1:5000/zhiputext", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          prompt: message.value,
        }),
      });

      const reader = response.body.getReader();
      const decoder = new TextDecoder("utf-8");

      let done = false;
      while (!done) {
        const {value, done: streamDone} = await reader.read();
        done = streamDone;

        // 将流数据解析为字符串并处理
        const chunk = decoder.decode(value, {stream: true});

        // 逐行处理每个流数据块
        chunk.split("\n").forEach((line) => {
          if (line.startsWith("data:")) {
            const text = line.replace("data:", "").trim();
            botMessage.text += text; // 拼接当前 bot 消息
            messages.value = [...messages.value]; // 强制更新 messages
          }
        });
      }
    } catch (error) {
      console.error("发送消息失败:", error);
    }

    message.value = ""; // 清空输入框
    imageFile.value = null; // 清空文件选择
    imagePreview.value = ""; // 清空图片预览
  }
};

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]; // 获取选中的文件
  if (file) {
    imageFile.value = file; // 将上传的文件保存到 imageFile 中
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreview.value = e.target.result; // 获取Base64编码的图片数据
    };
    reader.readAsDataURL(file); // 读取文件为DataURL
  }
};
</script>

<template>
  <div class="chat-container">
    <img :src="imagePreview" width="125" height="125" v-if="imagePreview"/>
    <div class="chat-box">
      <div class="messages">
        <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message', msg.user === 'me' ? 'sent' : 'received']"
        >
          <p>{{ msg.text }}</p>
        </div>
      </div>
      <div class="input-container">
        <input
            v-model="message"
            type="text"
            placeholder="请输入问题"
            class="input-box"
        />
        <input
            type="file"
            @change="handleFileChange"
            accept="image/*"
            style="display: none;"
            ref="fileInput"
        />

        <button style="background-color: #000000" @click="sendMessage" class="send-button">
          <svg t="1730172169588" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
               p-id="2617" width="16" height="16">
            <path
                d="M925.6 559.2L152 145.6c-11.2-5.6-24.8 3.2-23.2 15.2l60 714.4c0.8 11.2 12 17.6 22.4 13.6L460.8 784l136.8 155.2c8.8 9.6 24 5.6 27.2-6.4l65.6-245.6 235.2-99.2c11.2-5.6 12-22.4 0-28.8z m-328 305.6l-72-128-368-568 488 504-48 192z"
                p-id="2618" fill="#e6e6e6"></path>
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  background-color: #f0f2f5;
}

.chat-box {
  width: 100%;
  max-width: 800px;
  height: 100%;
  max-height: 700px;
  background-color: #ffffff;
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 15px;
}

.message {
  max-width: 75%;
  margin-bottom: 10px;
  padding: 10px 15px;
  border-radius: 12px;
  font-size: 16px;
  line-height: 1.5;
  background-color: #e1e1e1;
}

.sent {
  align-self: flex-end; /* 右对齐用户发送的消息 */
  background-color: rgb(255, 255, 255);
}

.received {
  align-self: flex-start; /* 左对齐接收到的消息 */
  background-color: rgb(235, 235, 235);
}

.input-container {
  display: flex;
  align-items: center;
  border-top: 1px solid #ddd;
  padding-top: 10px;
}

.input-box {
  flex: 1;
  padding: 12px;
  border-radius: 20px;
  border: 1px solid #ccc;
  outline: none;
  font-size: 16px;
}

.input-box:focus {
  border-color: #007bff;
}

.send-button {
  background-color: #007bff;
  color: #ffffff;
  border: none;
  border-radius: 20px;
  padding: 10px 20px;
  margin-left: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.send-button:hover {
  background-color: #0056b3;
}

.upload-button {
  background-color: #f0f0f0;
  border: none;
  border-radius: 20px;
  padding: 10px 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  margin-left: 10px;
  transition: background-color 0.3s ease;
}

.upload-button:hover {
  background-color: #e0e0e0;
}
</style>
